----------------------
-- ScreenManager class
----------------------
ScreenManager = {}
ScreenManager.__index = ScreenManager

function ScreenManager.new()
    local sm = {}
    setmetatable(sm, ScreenManager)
    
    -- variables
    sm.screens = {}
    
    return sm
end

-- get size
function ScreenManager:screenCount()
    return #self.screens
end

----------------------
-- Update
----------------------
function ScreenManager:update()
    if #self.screens == 0 then return end

    for i = 1, #self.screens do
        self.screens[i]:update()
    end
end

----------------------
-- Draw
----------------------
function ScreenManager:draw()
    if #self.screens == 0 then return end
    
    for i = 1, #self.screens do
         self.screens[i]:draw()
    end
end

----------------------
-- Loads screen with fading
-- this removes everything else from the list
-- and adds the new screen into the list
----------------------
function ScreenManager:loadScreen(screen)
    local c_screen = nil
    if #self.screens ~= 0 then c_screen = self.screens[1] end
    self.screens = {}
    dprint("ScreenManager", "Removed all screens, if there was any")
    
    table.insert(self.screens, LoadingScreen.new(c_screen, screen))
    
    dprint("ScreenManager", "Start loading next screen")

    --screen:loadContent()
    --table.insert(self.screens, screen)
end

----------------------
-- Push screen (popup)
-- adds screen into the list, does not 
-- remove other screens.
----------------------
function ScreenManager:pushScreen(screen)
    if screen == nil then 
    	dprint("ScreenManager", "Cannot add screen because it is nil") 
    	return 
    end
    
    if #self.screens == 2 then
    	dprint("ScreenManager", "Cannot add screen due to size limit (2) is already reached")
    	return
    end
    
    table.insert(self.screens, screen)
    
    dprint("ScreenManager", "Screen added")
end

----------------------
-- Removes screen
----------------------
function ScreenManager:removeScreen(index)
    if index < 1 and index > #self.screens then return end
    
    table.remove(self.screens, index)
    
    dprint("ScreenManager", "Screen removed (" .. index .. ")")
end

----------------------
-- Key pressed
----------------------
function ScreenManager:updateKeyPress(key)
    if #self.screens == 0 then return end
    -- update only the latest screen
    self.screens[#self.screens]:updateKeyPress(key)
end

----------------------
-- Key released
----------------------
function ScreenManager:updateKeyRelease(key)
    if #self.screens == 0 then return end
    -- update only the latest screen
    self.screens[#self.screens]:updateKeyRelease(key)
end
